<template>
    <div></div>
</template>
<script>
export default {
    name:'webosocket',
    data(){
        return {
            webSocket:null
        }
    },
    created() {
        // 页面打开就建立连接，根据业务需要
        this.initSocket()
    },
    destroyed() {
        // 页面销毁关闭连接
        this.webSocket.close()
    },
    methods:{
        initSocket(){
            // 有参数的情况下：
            let url = 'ws://192.168.0.93:8889/'+'jy/websocket';
            this.webSocket = new WebSocket(url)
            this.webSocket.onopen = this.webSocketOnOpen
            this.webSocket.onclose = this.webSocketOnClose
            this.webSocket.onmessage = this.webSocketOnMessage
            this.webSocket.onerror = this.webSocketOnError

        },
        webSocketOnOpen(){
            // 建立连接成功后的状态
            console.log('websocket连接成功')
        }, 
         // 获取到后台消息的事件，操作数据的代码在onmessage中书写
        webSocketOnMessage(res){
            let self = this;
             self.$message({
                showClose: true,
                message: res.data,
                type: 'warning',
                duration:0,
                onClose(){
                    // self.webSocket.send('已阅读');
                }
            });
            // res就是后台实时传过来的数据
            console.log(res);
                //给后台发送数据
            this.webSocket.send("发送数据");
        },
        // 关闭连接
        webSocketOnClose(){
             console.log('websocket连接已关闭');
        },
        //连接失败的事件
        webSocketOnError(res){
            console.log('websocket连接失败');
            // 打印失败的数据
            console.log(res);
        }

    }
}
</script>
<style scoped>

</style>


